package cn.hyatt.auth.controller;

import cn.hyatt.auth.dto.auth.AuthInfo;
import cn.hyatt.auth.dto.auth.UserInfo;
import cn.hyatt.auth.dto.auth.UsernameLoginRequest;
import cn.hyatt.auth.dto.auth.VueRouter;
import cn.hyatt.auth.service.AuthService;
import cn.hyatt.auth.utils.SecurityUtil;
import cn.hyatt.core.dto.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 认证-控制器
 *
 * @author hyatt
 */
@Tag(name = "认证")
@ResponseBody
@RestController
@AllArgsConstructor
@RequestMapping
public class AuthController {

    private AuthService authService;

    @PostMapping("/login")
    @Operation(summary = "登录")
    public R<AuthInfo> login(HttpServletRequest request, @RequestBody UsernameLoginRequest loginRequest) {
        return R.ok(authService.usernameLogin(request, loginRequest));
    }

    @PostMapping("/logout")
    @Operation(summary = "注销")
    public R<Void> logout() {
        authService.logout();
        return R.ok();
    }

    @PostMapping("/refreshAuth")
    @Operation(summary = "刷新认证")
    public R<AuthInfo> refreshAuth(HttpServletRequest request) {
        return R.ok(authService.refreshAuth(request));
    }

    @PostMapping("/base64Captcha")
    @Operation(summary = "Base64验证码")
    public R<String> base64Captcha(HttpServletRequest request) throws IOException {
        return R.ok(authService.getBase64Captcha(request));
    }

    @PostMapping("/imageCaptcha")
    @Operation(summary = "图片验证码")
    public ResponseEntity<InputStreamResource> imageCaptcha(HttpServletRequest request) throws IOException {
        ByteArrayOutputStream outputStream = authService.createCaptchaImageOutputStream(request);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);

        // 创建InputStreamResource对象并返回
        InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(outputStream.toByteArray()));
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }

    @GetMapping("/getUserInfo")
    @Operation(summary = "获取当前用户信息")
    public R<UserInfo> getUserInfo() {
        return R.ok(authService.getUserInfo(SecurityUtil.getUserId()));
    }

    @GetMapping("/getRouters")
    @Operation(summary = "获取当前用户路由")
    public R<List<VueRouter>> getRouters() {
        return R.ok(authService.getRouters(SecurityUtil.getUserId()));
    }
}
